#!/bin/bash

# input
read -p "Please enter Nodejs version (default: 16.18.1):" NODEJS_VERSION

read -p "Please enter the user name to config Nodejs env (default: root):" USERNAME

if [ -z "$NODEJS_VERSION" ]; then
    NODEJS_VERSION="16.18.1"
fi

if [ -z "$USERNAME" ]; then
    USERNAME=$HOME
else
    USERNAME=/home/$USERNAME
fi

check_command() {
    command -v "$1" >/dev/null
    if [ $? -ne 0 ]; then
        echo "Command not found, please install $1 command and try again."
        exit 1
    fi
}

get_os_type() {
    if [ "$(uname)" == "Darwin" ]; then
        os="darwin"
    elif [ "$(uname)" == "Linux" ]; then
        os="linux"
    else
        echo "Failed to get system type."
        exit 1
    fi
}

get_arch() {
    if [ $(arch) == "x86_64" ]; then
        arch="x64"
    elif [ $(arch) =~ "aarch64" ]; then
        arch="arm64"
    else
        echo "Failed to get system arch."
        exit 1
    fi
}

install_nodejs() {
    wget --user-agent="Mozilla" https://mirrors.ustc.edu.cn/node/v"$NODEJS_VERSION"/node-v"$NODEJS_VERSION"-"$os"-"$arch".tar.gz

    tar -zxvf node-v"$NODEJS_VERSION"-"$os"-"$arch".tar.gz -C /usr/local/

    rm -rf /usr/local/nodejs

    mv /usr/local/node-v"$NODEJS_VERSION"-"$os"-"$arch" /usr/local/nodejs

    rm -rf node-v"$NODEJS_VERSION"-"$os"-"$arch".tar.gz

    chown -R root /usr/local/nodejs

    chgrp -R root /usr/local/nodejs

    echo "export NODE_HOME=/usr/local/nodejs" >>$USERNAME/.bashrc
    echo -e "export PATH=\$PATH:\$NODE_HOME/bin" >>$USERNAME/.bashrc

    source $USERNAME/.bashrc

    node -v && npm -v
}

main() {
    check_command "wget"
    get_os_type
    get_arch
    install_nodejs
}

main
